/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#define DEVICE_ID "kangkang1"  // 定义设备 ID，用来唯一标识当前设备
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

volatile int light = 0;  // 灯的初始亮度
#define AT24C02_ADDR 0x50  // EEPROM 的地址
volatile char cmd;  // 用于存放移动端发送过来的控制命令
char s[100];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int fputc(int ch, FILE* fp)
{
	HAL_UART_Transmit(&huart1, (uint8_t*)&ch, 1, 1000);  // 发送不用中断。最后一个参数是超时时间，返回hal成功
	return ch;
}

void led_show(void)  // 灯的亮灭
{
	for(int i = 0; i < 100; i ++)
	{
		if(i < light)  // 灯亮
		{
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_SET);
		}
		else  // 灯灭
		{
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET);
		}
	}
}

void my_delay(uint32_t wait)  // 延时函数在等待时间到的时候，持续执行刷新灯的亮度
{
	uint32_t start = HAL_GetTick();
	
	while((HAL_GetTick() - start) < wait)
		led_show();
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
	
	//HAL_UART_Receive_IT(&huart1, (uint8_t*)&cmd, sizeof(cmd));
	HAL_UART_Receive_IT(&huart2, (uint8_t*)&cmd, sizeof(cmd));
	
	if(HAL_OK == HAL_I2C_Mem_Read(&hi2c1, AT24C02_ADDR << 1, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&light, 1, 10))
	{
		if(!(light >= 0 && light <= 100 && light % 20 == 0))
			light = 20;  // 如果没有读到灯的亮度，默认亮度为百分之二十
	}

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	
  while (1)
  {
		led_show();

		sprintf(s, DEVICE_ID"/state/light %d\n", light);
		HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);

		if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3) == GPIO_PIN_RESET)  // 增加亮度的按键按下
		{
			my_delay(5);  // 消抖的时间也持续刷新灯的亮度，而不是执行空语句
			
			if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3) == GPIO_PIN_RESET)  // 确认增加亮度的按键按下
			{
				light += 20;  // 灯的亮度增加
				
				if(light > 100) light = 100;  
				
				// 将亮度档位写入 EEPROM 保存
				HAL_I2C_Mem_Write(&hi2c1, AT24C02_ADDR << 1, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&light, 1, 10);

				sprintf(s, DEVICE_ID"/state/light %d\n", light);
				HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
				
				while(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3) == GPIO_PIN_RESET)  // 解决办法：在等待按键松开的时候，灯的亮度也继续刷新
					led_show();
			}
		}
		else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_4) == GPIO_PIN_RESET)
		{
			my_delay(5);
			
			if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_4) == GPIO_PIN_RESET)
			{
				light -= 20;
				
				if(light < 0) light = 0;
				
				// 将亮度档位写入 EEPROM 保存
				HAL_I2C_Mem_Write(&hi2c1, AT24C02_ADDR << 1, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&light, 1, 10);

				sprintf(s, DEVICE_ID"/state/light %d\n", light);
				HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
				
				while(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_4) == GPIO_PIN_RESET)
					led_show();
			}
		}
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if(huart == &huart2)
	{
    // 增加亮度
    if(cmd == 'u')
    {
			light += 20;
			if(light > 100) light = 100;
			
			led_show();
			HAL_I2C_Mem_Write(&hi2c1, AT24C02_ADDR << 1, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&light, 1, 10);
			
			// 上传亮度状态
			sprintf(s, DEVICE_ID"/state/light %d\n", light);
			HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
    }
    // 降低亮度
    else if(cmd == 'd')
    {
      light -= 20;
			if(light < 0) light = 0;
			
			led_show();
			HAL_I2C_Mem_Write(&hi2c1, AT24C02_ADDR << 1, 0, I2C_MEMADD_SIZE_8BIT, (uint8_t*)&light, 1, 10);
			
			// 上传亮度状态
			sprintf(s, DEVICE_ID"/state/light %d\n", light);
			HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
    }
		// 打开台灯（最大亮度）
		else if(cmd == 'o')
		{
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_SET);
			
			light = 100;
			// 上传亮度状态
			sprintf(s, DEVICE_ID"/state/light %d\n", light);
			HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
		}
		// 关闭台灯（没有亮度）
		else if(cmd == 's')
		{
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
			HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET);
			
			light = 0;
			// 上传亮度状态
			sprintf(s, DEVICE_ID"/state/light %d\n", light);
			HAL_UART_Transmit(&huart2, (uint8_t*)s, strlen(s), 1000);
		}
    // 继续接收数据
    HAL_UART_Receive_IT(&huart2, (uint8_t*)&cmd, sizeof(cmd));
	}
}


/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
